<template>
    <div class="chat">
        <div class="head">
            <div class="outer">
               <div class="back" @click="backUp">返回备课大厅</div>
            </div>
            <div class="title">教案设计界面</div>
            <div class="outer-save">
               <div class="save">保存AI教案设计</div>
            </div>
        </div>
        <div class="content">
           <div class="left">
              <div class="top">
                <div class="current">当前教案</div>
                <div class="left-save" @click="savePlan">保存教案内容</div>
                <SaveDialog v-if="confirmSave" class="save-dialog"></SaveDialog>
              </div>
              <div id="html-content-container" class="lesson" v-html="fullHtmlContent"></div>
              <div class="bottom">
                <div class="history">查看历史版本</div>
                <div class="preview">预览教案内容</div>
              </div>
           </div>
           <div class="right">
              <div class="right-head">AI备课助手对话框</div>
              <div class="chat-box">
                 <Chat :messages="messages"></Chat>
              </div>
              <div class="function-outer">
                <textarea v-model="input" class="message-textarea"
                placeholder="给小贝发送消息" placeholder-class="textarea-placeholder"></textarea>
                <div class="function-box">
                    <div class="box">
                      <div class="copy" @click="copyInput"></div>
                      <div class="enter" @click="sendMessage"></div>
                    </div>
                </div>
              </div>
           </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import Chat from '@/views/ai-chat/components/chat.vue'
import SaveDialog from '@/views/ai-chat/components/save-dialog/save.vue'
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { useSearchStore } from '@/stores/search';
const route = useRoute()
const router = useRouter()
const searchStore = useSearchStore()
const input = ref('')
const form = ref({
  type: 'TeachingPlan',
  user: ''
})
const confirmSave = ref(false)
const messages = ref([
  { text: "Hello，我是您的备课助手小贝! 很乐意为您服务，有什么可以帮您的吗？", isUser: false }
]);
const fullHtmlContent = ref('');
// 创建WebSocket对象并指定服务器地址
const socket = ref<WebSocket | null>(null);
onMounted(() => {
  socket.value = new WebSocket('ws://localhost:5174/ws');
  socket.value.onopen = function () {
    console.log("WebSocket连接已建立");
    const { type, message } = route.query;
    if (message) {
      form.value.type = type as string || 'TeachingPlan';
      form.value.user = message as string;
      socket.value!.send(JSON.stringify(form.value));
      messages.value.push({ text: message as string, isUser: true });
      messages.value.push({ text: "好的，小贝这就为您生成一份对应的专属教案", isUser: false });
    }
  };

  socket.value.onmessage = function (event) {
    const message = event.data;
    console.log("接收到服务器发送的消息：" + message);
    const htmlTemplate = `${message}`
    // 将生成的完整 HTML 内容赋值给 fullHtmlContent
    fullHtmlContent.value = htmlTemplate;
    messages.value.push({ text: "已经生成了对应的教案。是否还有需要修改的地方，可以告诉小贝！", isUser: false });
  };

  socket.value.onclose = function (event) {
    console.log("WebSocket连接已关闭");
  };

  socket.value.onerror = function (event) {
    console.error("WebSocket连接错误：" + event);
  };
});

onUnmounted(() => {
  if (socket.value) {
    socket.value.close();
  }
});

function sendMessage(){
  if (input.value.trim() !== '') {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      form.value.type = 'TeachingPlan';
      form.value.user = input.value;
      socket.value.send(JSON.stringify(form.value));
      messages.value.push({ text: input.value, isUser: true });
      messages.value.push({ text: "好的，小贝这就为您生成一份对应的专属教案", isUser: false });
      input.value = '';
    }
  }
}

async function copyInput(){
  if (input.value.trim() !== '') {
    await navigator.clipboard.writeText(input.value);
  }
}

function savePlan(){
  confirmSave.value = !confirmSave.value
}

function backUp(){
  router.push('/')
  searchStore.searchInput = ''
}
</script>

<style scoped lang="less">
@import url('@/views/ai-chat/index.less');
</style>